package top.atcra.dubbo;

import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.ReferenceConfigBase;
import org.apache.dubbo.config.RegistryConfig;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class Consumer {
    volatile static long start;

    public static void main(String[] args) {
        //1、application
        ApplicationConfig applicationConfig = new ApplicationConfig("sample-consumer");
        //2、配置reference
        ReferenceConfigBase<SayHello> referenceConfig = new ReferenceConfig<>();
        referenceConfig.setApplication(applicationConfig);
        referenceConfig.setInterface(SayHello.class);

        RegistryConfig registryConfig = new RegistryConfig("zookeeper://npu1.atcra.top:2181");
        referenceConfig.setRegistry(registryConfig);


        // 4. 调用远程方法
        int THREAD_NUM = 32, CALL_PER_THREAD = 100;
        int totalCount = THREAD_NUM * CALL_PER_THREAD;
        AtomicInteger errorCount = new AtomicInteger(0);
        CountDownLatch countDownLatch = new CountDownLatch(THREAD_NUM);
        try (ExecutorService pool = Executors.newFixedThreadPool(THREAD_NUM)) {
            for (int i = 0; i < THREAD_NUM; i++) {
                pool.execute(() -> {
                    SayHello proxy = referenceConfig.get();
                    countDownLatch.countDown();
                    try {
                        countDownLatch.await();
                        start = System.currentTimeMillis();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    for (int j = 0; j < CALL_PER_THREAD; j++) {
                        try {
                            var result = proxy.sayHello("atcra");
                        } catch (Exception e) {
//                            errorCount.incrementAndGet();
                        }
                    }
                });
            }
            pool.shutdown();
            System.out.println(pool.awaitTermination(123456, java.util.concurrent.TimeUnit.SECONDS));
            long end = System.currentTimeMillis();
            System.out.printf("QPS: %f,Error rate: %f. \n", (double) totalCount * 1000 / (end - start), (double) errorCount.get() / totalCount);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
